// ClientSocket.cpp : implementation file
//

#include "stdafx.h"
#include "Server.h"
#include "ClientSocket.h"
#include "ServerDlg.h"
#include "Config.h"


// ClientSocket
int offset;
ClientSocket::ClientSocket()
: m_port(0)
, m_ipAddress(_T(""))
, pDlg(NULL)
{
	buff_tmp = NULL;
	offset = 0;
}

ClientSocket::~ClientSocket()
{
}


// ClientSocket member functions

void ClientSocket::OnSend(int nErrorCode)
{
	OutputDebugString(_T("[S-Client socket] OnSend()"));
	CSocket::OnSend(nErrorCode);
}

void ClientSocket::OnConnect(int nErrorCode)
{

	CSocket::OnConnect(nErrorCode);
}

void ClientSocket::OnReceive(int nErrorCode)
{
	OutputDebugString(_T("[S-Client socket]: OnReceive"));

	CString text;
	((CServerDlg*)pDlg)->GetDlgItemText(IDC_EDIT_RECEIVE_MSG, text);

	char* buff = ((CServerDlg*)pDlg)->m_szBuff;
	int receiveLen = Receive(buff, BUFF_SIZE);

// 	int t1 = (int)ReadINT8((byte*)buff, 0);
// 	int a1 = (int)ReadINT8((byte*)buff, 1);
// 	int size1 = (int)ReadINT32((byte*)buff, 2);
// 	OutputDebugString(_T("dialog receive buffer"));
// 	char s1[256];
// 	sprintf(s1, "BUFF: %d %d %d", t1, a1, size1);
// 	OutputDebugStringA(s1);

	int dataSize = ReadINT32((byte*)buff, 2);
	((CServerDlg*)pDlg)->m_receiveSize = receiveLen;
	CString str;
	str.Format(_T("%d"), receiveLen);
	OutputDebugString(_T("reciveLen") + str);
	text += "\r\n";
	text += str;
	((CServerDlg*)pDlg)->SetDlgItemText(IDC_EDIT_RECEIVE_MSG, text);

	if(receiveLen < BUFF_SIZE)
	{
		if(buff_tmp == NULL)
		{
			OutputDebugString(_T("cap phat vung nho"));
			offset = 0;
			buff_tmp = new byte[BUFF_SIZE];
		}
		memcpy(buff_tmp + offset, buff, receiveLen);
		offset += receiveLen;
		if(offset >= BUFF_SIZE)
		{
			OutputDebugString(_T("********"));
			//((CServerDlg*)pDlg)->SetDlgItemText(IDC_EDIT_RECEIVE_MSG, _T("*******************"));
			int t = (int)ReadINT8(buff_tmp, 0);
			int a = (int)ReadINT8(buff_tmp, 1);
			int size = (int)ReadINT32(buff_tmp, 2);
			OutputDebugString(_T("dialog receive buffer"));
			char s[256];
			sprintf(s, "BUFF: %d %d %d", t, a, size);
			OutputDebugStringA(s);
			memcpy(buff, buff_tmp, BUFF_SIZE);
			//((CServerDlg*)pDlg)->OnReceive((char*)buff_tmp,BUFF_SIZE);
			((CServerDlg*)pDlg)->OnReceive(buff,BUFF_SIZE);
			OutputDebugString(_T("dialog receive buffer - END"));
			delete buff_tmp;
			buff_tmp = NULL;
		}
	}
	else
	{
		((CServerDlg*)pDlg)->OnReceive(buff,BUFF_SIZE);
	}


//	((CServerDlg*)pDlg)->OnReceive(buff,BUFF_SIZE);
	//OutputDebugStringA(buff);

	CSocket::OnReceive(nErrorCode);
}
